<template>
  <div>
    <el-button type="primary" @click="add"> 添加</el-button>
    <el-table :data="tableData" style="width: 100%">
      <!-- <el-table-column prop="url" label="图片" /> -->
      <el-table-column prop="url" label="图片">
        <template #default="scope">
          <el-image :src="scope.row.url" style="width: 273px; height: 93px;cursor: pointer;" @click="openPhotos(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="content" label="内容" >
        <template #default="scope">
        <div v-html="scope.row.content"></div>
        </template>
        </el-table-column>
      <el-table-column prop="" label="操作">
        <template #default="scope">
          <el-button type="primary" link @click="edit(scope.row)">修改</el-button>
          <el-popconfirm title="确定要删除吗?" confirm-button-text="确定" cancel-button-text="取消" @confirm="del(scope.row)">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="Tips" width="50%">
      <el-form :model="form" label-width="120px" style="margin-right: 30px;">
        <el-form-item label="上传">
          <el-upload v-model:file-list="fileList" accept=".jpg,.png,.gif" method="post" :on-success="on_success" class="upload-demo" action="http://47.92.249.56:3006/upload?path=cooperation"
            :on-preview="handlePreview" :on-remove="handleRemove" :on-exceed="handleExceed">
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                仅支持 jpg/png/gif
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="路径">
          <el-input v-model="form.url" disabled />
        </el-form-item>
        <el-form-item label="内容">
          <!-- <el-input v-model="form.content" /> -->

          <div>
            <Toolbar style="margin-bottom: 10px;" :editor="editorRef_detail" :defaultConfig="toolbarConfig" :mode="'default'" />
            <Editor style="height: 200px; overflow-y: hidden;border: 1px solid #ccc;" v-model="form.content" :defaultConfig="editorConfig" :mode="'default'" @onCreated="handleCreatedDetail" />

          </div>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="enter_add">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref, shallowRef } from 'vue'
import http from '../../../http'
import { useCounterStore } from '../../../current/index'
import { storeToRefs } from 'pinia' // cnpm i pinia --save  2.1.3
import axios from 'axios'
import { layer } from '@layui/layui-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const store = useCounterStore()
const { userInfo } = storeToRefs(store) //  数据

const editorRef = shallowRef()
const editorRef_detail = shallowRef()

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
const handleCreatedDetail = (editor) => {
  editorRef_detail.value = editor
}
const toolbarConfig = {
  excludeKeys: [
    'group-image',
    'group-video',
    'blockquote',
    'bulletedList',
    'numberedList',
    'insertTable',
    'codeBlock',
    'fullScreen'
  ]
}
const editorConfig = { placeholder: '请输入内容...' }

onMounted(() => {
  get_list()
  get_cooperlist()
})
const dialogVisible = ref(false)
const form = reactive({
  url: '',
  content: '',
  title: ''
})

const id = ref('')
const is_add_edit = ref('')
// 添加
const add = () => {
  form.url = ''
  form.content = ''
  form.title = ''
  is_add_edit.value = 'add'
  dialogVisible.value = true
}
const enter_add = async () => {
  if (form.url == '' || form.content == '') {
    ElMessage.error('路径和内容不能为空')
    return false
  }
  if (is_add_edit.value == 'add') {
    const res = await adminsql(
      `INSERT INTO webcooperation (url,content,title) VALUES('${form.url}','${form.content}','${form.title}')`,
      'website'
    )
    console.log(res)
    if (res == '成功') {
      ElMessage.success('添加成功')
      dialogVisible.value = false
    }
  } else if (is_add_edit.value == 'edit') {
    const res = await adminsql(
      `update  webcooperation set url = '${form.url}',content = '${form.content}' where id = '${id.value}'`,
      'website'
    )
    console.log(res)
    if (res == '成功') {
      ElMessage.success('修改成功')
      dialogVisible.value = false
    }
  }

  await get_list()
}

const openPhotos = function (row) {
  layer.photos({
    imgList: [
      {
        src: row.url,
        alt: '图片'
      }
    ]
  })
}

// 修改
const edit = (row) => {
  form.url = row.url
  form.content = row.content
  is_add_edit.value = 'edit'
  id.value = row.id
  dialogVisible.value = true
}
// 删除
const del = async (row) => {
  const res = await adminsql(`delete from webcooperation where id = '${row.id}'`, 'website')
  if (res == '成功') {
    ElMessage.success('删除成功')
  }
  await get_list()
}

const get_cooperlist = () => {
  // axios({
  //   url: 'http://47.92.249.56:3006/imglist?path=cooperation',
  //   method: 'get'
  // }).then((res) => {
  //   console.log(res.data.data)
  //   console.log(tableData.value)
  //   let sql_arr = []
  //   for (var i = 0; i < tableData.value.length; i++) {
  //     sql_arr.push(tableData.value[i].url.split('cooperation/')[1])
  //   }
  //   console.log(sql_arr)
  //   let endarr = res.data.data.filter((item) => !sql_arr.includes(item))
  //   console.log(endarr)
  // endarr.forEach(async (element) => {
  //   await del_upload(element)
  // })
  // })
}

const del_upload = async (name) => {
  console.log(name)
  const res = await http.website_corsApi('/delete', 'post', { path: 'cooperation/' + name })
  console.log(res)

  // axios.post('http://localhost:3006/delete',{path:'material/'+row.name})
}

// 表格
const tableData = ref([])
const get_list = async () => {
  const res = await adminsql(`select* from webcooperation`, 'website')
  if (res == '成功') {
    tableData.value = []
  } else {
    let arr = JSON.parse(res)
    tableData.value = arr
  }
  console.log(res)
}

const fileList = ref([])

const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview = (uploadFile) => {
  console.log(uploadFile)
}

const on_success = async (response, uploadFile, uploadFiles) => {
  console.log(response)
  ElMessage.success(response.msg)
  form.url = response.url
  //   await get_banner()
}

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  )
}

const adminsql = async (sql, dbName) => {
  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: sql,
      dbName: dbName
    }
  })
  console.log(res)

  let result = null
  if (res.packageContent.packageStatus == 0) {
    result = res.packageContent.packageMsg
  }

  return result
}

defineExpose({
  get_list,
  get_cooperlist
})
</script>

<style scoped>
</style>